package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.common.TokenHolder;
import com.itheima.domain.ShoppingCart;
import com.itheima.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author CSY
 * 2022/5/12    15:33
 */
@RestController
@Slf4j
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 购物车展示
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){

        List<ShoppingCart> shoppingCarts = shoppingCartService.shoppingCarts();


        return R.success(shoppingCarts);
    }

    @Transactional
    @PostMapping("/add")
    public R<List<ShoppingCart>> add(@RequestBody ShoppingCart shoppingCart){

        shoppingCart.setUserId(Long.valueOf(TokenHolder.getCurrentId()));
        //TODO 先判断商品是否存在，存在则修改数量（数量+1），不存在则则添加  完成

        boolean b1 = shoppingCartService.getdishByUidDishid01(shoppingCart);

        if (b1){

            boolean b = shoppingCartService.updateNumber(shoppingCart);
            List<ShoppingCart> shoppingCarts = shoppingCartService.selectShoppCartByUserId();
            return b?R.success(shoppingCarts):R.error("修改失败");
        }else {

            boolean b = shoppingCartService.shoppingCartAdd(shoppingCart);

            if (b){
                List<ShoppingCart> shoppingCarts = shoppingCartService.selectShoppCartByUserId();
                return R.success(shoppingCarts);
            }
        }

        return R.error("数据有误");
    }

    @DeleteMapping("/clean")
    public R<String> clean(){

        boolean delete = shoppingCartService.delete();

        return delete?R.success("清空购物车成功"):R.error("清空失败");
    }

    @PostMapping("/sub")
    public R<String> sub(@RequestBody ShoppingCart shoppingCart){


        //TODO  每一次sub减少都number-1 直到  number=0 直接删除 相关购物车内容

        boolean sub = shoppingCartService.sub(shoppingCart);

        return sub?R.success("成功"):R.error("失败");
    }

}
